package main

import (
	"context"
	"fmt"
	"go.mongodb.org/mongo-driver/bson"
	"log"

	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

type IdDept struct {
	Dept string
	Age  int
}

type ResultDept struct {
	_id IdDept
	// Pers int
	DeptAvgSalary int
}

func main() {
	// 设置客户端连接配置
	clientOptions := options.Client().ApplyURI("mongodb://127.0.0.12.9:27017")

	// 连接到MongoDB
	client, err := mongo.Connect(context.TODO(), clientOptions)
	if err != nil {
		log.Fatal(err)
	}

	// 检查连接
	err = client.Ping(context.TODO(), nil)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("Connected to MongoDB!\n")

	// 获取集合
	persons := client.Database("test").Collection("persons")

	// Start Aggregation Example 12.9
	pipeline := mongo.Pipeline{
		{
			{"$project", bson.D{
				{"age", 1},
				{"dept", 1},
				{"oldSalary", "$salary"},
				{
					"salary",
					bson.D{{"$switch",
						bson.D{{"$branches", []interface{}{
							bson.D{{"$case", 10000}},
							bson.D{{"$then", 4000}},
						}}}},
						{"$default", "$salary"},
					},
				},
			}},
		},
	}

	cur, err := persons.Aggregate(context.TODO(), pipeline)
	if err != nil {
		log.Fatal(err)
	}
	// 定义一个切片用来存储结果
	var results []*ResultDept
	// 查找多个文档返回一个光标
	// 遍历游标允许我们一次解码一个文档
	for cur.Next(context.TODO()) {
		// 创建一个值，将单个文档解码为该值
		// var elem ResultDept
		var elem map[string]interface{}
		err := cur.Decode(&elem)
		if err != nil {
			log.Fatal(err)
		}
		fmt.Printf("Found multiple document: %+v\n", elem)
		// results = append(results,&elem)
	}

	if err := cur.Err(); err != nil {
		log.Fatal(err)
	}

	// 完成后关闭
	cur.Close(context.TODO())
	fmt.Printf("\nAggregate multiple documents (array of pointers): %+v\n\n", results)

	// Close the connection once no longer needed
	err = client.Disconnect(context.TODO())

	if err != nil {
		log.Fatal(err)
	} else {
		fmt.Println("\nConnection to MongoDB closed.")
	}
}
